import sys
import subprocess

redis = 'redis-server'
configPath = './config'
redisConfig = 'redis.conf'
redisConfigPath = './conf/redis.conf'

def GetRedisPid():
    try:
        result = subprocess.run(['pgrep', '-f', redis], check=True, stdout=subprocess.PIPE, text=True)
        if result.stdout.strip():
            return result.stdout.split();
        return None
    except subprocess.CalledProcessError:
        return None

def StartRedis():
    if GetRedisPid():
        print('Redis is already running, not start again.')
        return

    try:
        subprocess.run([redis, redisConfigPath], check=True, text=True)
        print('Start redis success.')
    except subprocess.CalledProcessError:
        print('Start redis success.')

def StopRedis():
    pids = GetRedisPid()
    if pids:
        try:
            subprocess.run(['sudo', 'kill'] + pids, check=True)
            print('Stop redis success.')
        except subprocess.CalledProcessError:
            print('Stop redis failed.')
    else:
        print('Redis is not running.')
    return

def StatusRedis():
    pids = GetRedisPid()
    if pids:
        print('Redis is running.')
    else:
        print('Redis is not running.')


def main():
    if len(sys.argv) < 2:
        print('Please input the operation.')
        sys.exit(0)
    
    operation = sys.argv[1]
    if 'start' == operation:
        StartRedis()
    elif 'stop' == operation:
        StopRedis()
    elif 'status' == operation:
        StatusRedis()
    else:
        print('Operation is failed, please input the correct operation.')
        sys.exit(0)

if __name__ == '__main__':
    main()